package com.atguigu.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.config.YyghException;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.service.OrderService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.RefundService;
import com.atguigu.yygh.order.service.WXService;
import com.atguigu.yygh.order.utils.HttpClient;
import com.atguigu.yygh.order.utils.WXProperties;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhmwi
 * @Date 2021/7/23
 * @Dersciption
 */
@Service
public class WXServiceImpl implements WXService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private RefundService refundService;

    //下单 生成二维码
    @Override
    public Map createNative(Long orderId) {
        //二维码有时效性 俩小时有效 可以借助Redis保存
        //可以先查询redis有没有已生成的微信支付码
        Map nativeMap = (Map) redisTemplate.opsForValue().get(orderId.toString());
        if (nativeMap != null){
            //从Redis中取出直接返回
            return nativeMap;
        }

        //根据orderId查询订单信息
        OrderInfo orderInfo = orderService.getById(orderId);
        if (orderInfo == null){
            throw new YyghException(20001,"下单参数无效");
        }

        //保存交易记录
        paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());

        //封装生成二维码的参数
        Map paramMap = new HashMap();
        paramMap.put("appid", WXProperties.APPID);//应用id
        paramMap.put("mch_id", WXProperties.PARTNER);//商户号
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());//微信自己生成随机编号
        String body = orderInfo.getReserveDate() + "就诊"+ orderInfo.getDepname();
        paramMap.put("body", body);
        paramMap.put("out_trade_no", orderInfo.getOutTradeNo());//交易流水号
        //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
        paramMap.put("total_fee", "1");//为了测试
        paramMap.put("spbill_create_ip", "127.0.0.1");
        paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");//回调地址,外网IP
        paramMap.put("trade_type", "NATIVE");
        try {
            //创建client对象
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //向client对象存入参数(1、封装好的参数，2、商户秘钥)
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,WXProperties.PARTNERKEY));
            //设置用https协议，用post方式发送
            client.setHttps(true);
            client.post();
            //从client获取返回结果
            String xml = client.getContent();
            System.out.println("xml = " + xml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            //封装最终返回结果
            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));

            //将返回结果 保存到数据库一份
            redisTemplate.opsForValue().set(orderId.toString(),map);
            return map;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap();
    }

    //查询支付状态
    @Override
    public Map<String, String> getPayStatus(Long orderId, Integer paymentType) {
        //根据orderId查询订单详情
        OrderInfo orderInfo = orderService.getById(orderId);
        if (orderInfo == null){
            throw new YyghException();
        }
        //封装查询参数
        Map paramMap = new HashMap<>();
        paramMap.put("appid", WXProperties.APPID);
        paramMap.put("mch_id", WXProperties.PARTNER);
        paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

        try {
            //创建client对象
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            //向client对象存入参数(1、封装好的参数，2、商户秘钥)
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,WXProperties.PARTNERKEY));
            //设置用https协议，用post方式发送
            client.setHttps(true);
            client.post();
            String xml = client.getContent();
            System.err.println("xml --"+xml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            return resultMap;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Boolean refund(Long orderId) {
        try {
            //查询交易记录
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            //创建退款记录
            RefundInfo refundInfo = refundService.saveRefundInfo(paymentInfo);
            //判断退款状态
            if(refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return true;
            }
            //封装参数
            Map<String,String> paramMap = new HashMap<>(8);
            paramMap.put("appid",WXProperties.APPID);       //公众账号ID
            paramMap.put("mch_id",WXProperties.PARTNER);   //商户编号
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
            //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee","1");
            paramMap.put("refund_fee","1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap,WXProperties.PARTNERKEY);
            //创建client
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            //设置参数，属性，发送
            client.setXmlParam(paramXml);
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(WXProperties.PARTNER);
            client.post();
            //获取参数
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

